"""
查找替换嵌套的 date_add 函数
"""

import logging
import re


def change_current_day_add_add_df_day_hyphen(m):
    new_date_format = "TO_CHAR((CURRENT_DATE + INTERVAL '{} DAY') + INTERVAL '{} DAY' ,'yyyy-MM-dd')" \
        .format(str(m.group(6).strip()).replace("'", ""), str(m.group(9).strip()).replace("'", ""))
    return new_date_format


def change_current_day_add_day_hyphen(m):
    new_date_format = "TO_CHAR(CURRENT_DATE + INTERVAL '{} DAY','yyyy-MM-dd')" \
        .format(str(m.group(5).strip()).replace("'", ""))
    return new_date_format


def change_now_date_add_day(m):
    logging.info("change_now_date_add_day")
    add_day = int(str(m.group(4)).strip())
    if add_day < 0:
        logging.debug("是不是开发把 函数用错了 。。。。 ")
        new_date_format = "NOW() - INTERVAL '{} DAY'".format(abs(add_day))
    else:
        new_date_format = "NOW() + INTERVAL '{} DAY'".format(add_day)
    return new_date_format


def rep_complex_fn_date_add(document_content):
    """
    替换复杂嵌套的 date_format 函数
    :param document_content: 原始文本文件
    :return: 替换后的文本内容
    """
    # date_add(date_add(DATE_FORMAT(NOW(),'%Y-%m-%d'),interval 1 day),interval -30 day)
    df_patten = re.compile(
        r"([^\(]DATE_ADD|date_add)\((DATE_ADD|date_add)\((DATE_FORMAT|date_format)\((NOW|now)\(\),\'%Y-%m-%d\'\)\,(INTERVAL|interval) (.*) (DAY|day)\)\,(INTERVAL|interval) (.*) (DAY|day)\)")
    result = df_patten.sub(change_current_day_add_add_df_day_hyphen, document_content)
    document_content = result

    # date_add(DATE_FORMAT(NOW(),'%Y-%m-%d'), interval 2 day)
    df_patten = re.compile(
        r"([^\(]DATE_ADD|date_add)\((DATE_FORMAT|date_format)\((NOW|now)\(\)\,\'%Y-%m-%d\'\)\,(INTERVAL|interval) (.*) (DAY|day)\)")
    result = df_patten.sub(change_current_day_add_day_hyphen, document_content)
    document_content = result

    # date_add(NOW(),interval -90 DAY)
    # date_add(now(),interval -120 day)
    df_patten = re.compile(
        r"([^\(]DATE_ADD|date_add)\((NOW|now)\(\)\,(INTERVAL|interval)(.*)(DAY|day)\)")
    result = df_patten.sub(change_now_date_add_day, document_content)
    document_content = result

    return document_content
